class Solution(object):
    
    def removeDuplicates(self, nums):
        """
        方法：从已排序数组中删除重复项，使得每个元素最多出现两次
        
        Args:
            nums: List[int], 已排序的整数数组
            
        Returns:
            int: 新数组的长度 k，原数组的前 k 个元素为最终结果
            
        Time: O(n)，其中 n 是数组的长度，只需要一次遍历数组
        
        Space: O(1)，只使用了常数级的额外空间
        """
        length = len(nums)
        if length < 3:
            return length
        i = 2
        for j in range(2, length):
            if nums[j] != nums[i-2]:
                nums[i] = nums[j]
                i += 1
        return i
    
def test_remove_duplicates():
    solution = Solution()
    
    # 测试用例1：常规数组，包含重复元素超过两次
    nums1 = [1, 1, 1, 2, 2, 3]
    expected_len1 = 5
    expected_array1 = [1, 1, 2, 2, 3]
    result1 = solution.removeDuplicates(nums1)
    print("Test Case 1:")
    print(f"Expected: {expected_array1}, length = {expected_len1}")
    print(f"Actual: {nums1[:result1]}, length = {result1}")
    assert result1 == expected_len1, f"Length mismatch. Expected {expected_len1}, got {result1}"
    assert nums1[:result1] == expected_array1, f"Array mismatch. Expected {expected_array1}, got {nums1[:result1]}"
    
    # 测试用例2：空数组
    nums2 = []
    expected_len2 = 0
    result2 = solution.removeDuplicates(nums2)
    print("\nTest Case 2:")
    print(f"Expected: [], length = {expected_len2}")
    print(f"Actual: {nums2}, length = {result2}")
    assert result2 == expected_len2, f"Length mismatch. Expected {expected_len2}, got {result2}"
    
    # 测试用例3：所有元素都相同
    nums3 = [1, 1, 1, 1, 1]
    expected_len3 = 2
    expected_array3 = [1, 1]
    result3 = solution.removeDuplicates(nums3)
    print("\nTest Case 3:")
    print(f"Expected: {expected_array3}, length = {expected_len3}")
    print(f"Actual: {nums3[:result3]}, length = {result3}")
    assert result3 == expected_len3, f"Length mismatch. Expected {expected_len3}, got {result3}"
    assert nums3[:result3] == expected_array3, f"Array mismatch. Expected {expected_array3}, got {nums3[:result3]}"
    
    # 测试用例4：已经符合条件的数组
    nums4 = [1, 1, 2, 2, 3]
    expected_len4 = 5
    expected_array4 = [1, 1, 2, 2, 3]
    result4 = solution.removeDuplicates(nums4)
    print("\nTest Case 4:")
    print(f"Expected: {expected_array4}, length = {expected_len4}")
    print(f"Actual: {nums4[:result4]}, length = {result4}")
    assert result4 == expected_len4, f"Length mismatch. Expected {expected_len4}, got {result4}"
    assert nums4[:result4] == expected_array4, f"Array mismatch. Expected {expected_array4}, got {nums4[:result4]}"

if __name__ == "__main__":
    try:
        test_remove_duplicates()
        print("\nAll test cases passed successfully!")
    except AssertionError as e:
        print("\nTest failed:", str(e))
    